package com.yjf.wxapi.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.yjf.question.utils.ResultUtils;
import com.yjf.question.utils.ResultVo;
import com.yjf.wxapi.config.WxConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序登录的控制器
 */
@RestController
@RequestMapping("/wxapi/login")
public class LoginController {
    @Resource
    private WxConfig wxConfig;

    /**
     * 小程序登录
     * @param code
     * @return
     */
    @RequestMapping("/wxLogin")
    public ResultVo wxLogin(@RequestParam("code") String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid",wxConfig.getAppid());
        map.put("secret",wxConfig.getSecret());
        map.put("js_code",code);
        map.put("grant_type",wxConfig.getGrantType());
        //发送请求到微信接口服务获取openid
        String body = HttpRequest.get(wxConfig.getUrl()).form(map).body();
        JSONObject object = JSON.parseObject(body);
        return ResultUtils.success("获取成功",object);
    }
}
